package com.authine.cloudpivot.ext.utils;

import cn.hutool.core.util.NumberUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.authine.cloudpivot.ext.dto.GatewayParam;
import com.authine.cloudpivot.ext.dto.GatewayResponse;
import com.authine.mvp.app.launcher.domain.AddrFormat;
import com.authine.mvp.app.launcher.domain.AttachmentFormat;
import com.authine.mvp.app.launcher.domain.SelectorFormat;
import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

public class Utils {


    /**
     * 返回两数之和
     *
     * @param a1
     * @param a2
     * @return a1+a2
     */
    public static BigDecimal nwdBcadd(Object a1, Object a2) {
        BigDecimal accrual1 = new BigDecimal(a1.toString());
        BigDecimal accrual2 = new BigDecimal(a2.toString());
        BigDecimal accrual = accrual1.add(accrual2);
        return accrual;
    }

    /**
     * 返回两数之差
     *
     * @param a1
     * @param a2
     * @return a1-a2
     */
    public static BigDecimal nwdBcsub(Object a1, Object a2) {
        BigDecimal accrual1 = new BigDecimal(a1.toString());
        BigDecimal accrual2 = new BigDecimal(a2.toString());
        BigDecimal accrual = accrual1.subtract(accrual2);
        return accrual;
    }

    /**
     * 返回两数之积
     *
     * @param a1
     * @param a2
     * @return a1*a2
     */
    public static BigDecimal nwdMultiply(Object a1, Object a2) {
        BigDecimal accrual1 = new BigDecimal(a1.toString());
        BigDecimal accrual2 = new BigDecimal(a2.toString());
        BigDecimal accrual = accrual1.multiply(accrual2);
        return accrual;
    }

    /**
     * 返回两数相除
     *
     * @param a1
     * @param a2
     * @return a1/a2
     */
    public static BigDecimal nwdDivide(Object a1, Object a2) {
        MathContext mc = new MathContext(10, RoundingMode.HALF_DOWN); // 取字符个数为10
        BigDecimal accrual1 = new BigDecimal(a1.toString());
        BigDecimal accrual2 = new BigDecimal(a2.toString());
        BigDecimal accrual = accrual1.divide(accrual2, mc);
        return accrual;
    }

    /**
     * 返回小数点后2位
     *
     * @param object
     * @return .00
     */
    public static BigDecimal setScale(Object object) {
        BigDecimal bd = new BigDecimal(object.toString());
        bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP); // 取小数点后2位 /ROUND_HALF_UP
        return bd;
    }

    /**
     * 集合拼接为字符带“,”字符串
     * @param str
     * @return
     */
    public static String stringArray2Strin(List<String> str) {

        return "'".concat(StringUtils.join(str,"','")).concat("'");
    }

    /**
     *  集合里有一个元素值是为空
     * @param coll
     * @return
     */
    public static boolean listItemAnyIsNull(Collection coll){
        return coll.stream().anyMatch(a -> Objects.isNull(a));
    }

    /**
     *  sql like  value
     * @param val
     * @return
     */
    public static String likeVal(String val){
        return  "%".concat(val);
    }

    /**
     *  bool
     *  integer   1,0
     * @param val
     * @return
     */
    public static boolean parseObjToBool(Object val) {

        if (val == null) {
           return false;
        }

        if (val instanceof Boolean) {
            return (Boolean) val;
        } else if (val instanceof Integer) {
            if ((Integer) val == 1 || (Integer) val == 0) {
                return ((Integer) val) == 1;
            }
        }

        return false;
    }

    /**
     * 把符合SelectorFormat 的数据  SingleList , Map, String , 转为 SelectorFormat
     * 对于 单选组织, 数据库里是json 对象,但通过boService 获取到的是 SingleList
     *
     * @param obj
     * @return
     */
    public static SelectorFormat toSelectorFormat(Object obj) {

        if (obj == null) {
            return null;
        }


        String temp;
        if (obj instanceof List) {
            List list = ((List<?>) obj);

            if (list.size() == 0) {
                return null;
            }
            temp = JSON.toJSONString(list.get(0));
        } else if (obj instanceof String) {
            temp = (String) obj;
        } else {
            temp = JSON.toJSONString(obj);
        }


        return JSON.parseObject(temp, SelectorFormat.class);
    }


    /**
     * 创建selectFormat
     *
     * @param id
     * @param name
     * @param type
     * @return
     */
    public static SelectorFormat createSelecorFormat(String id, String name, int type) {
        SelectorFormat selectorFormat = new SelectorFormat();

        selectorFormat.setName(name);
        selectorFormat.setId(id);
        selectorFormat.setType(type);
        return selectorFormat;
    }

    /**
     * 判断云枢图片字段值是否相同
     * @param s
     * @param s2
     * @return
     */
    public static boolean imageEquals(Object s, Object s2) {

        if (s == null && s2 == null) {
            return true;
        }

        if (s == null) {
            return false;
        }

        if (s2 == null) {
            return false;
        }

        if (!(s instanceof List)) {
            return false;
        }
        if (!(s2 instanceof List)) {
            return false;
        }
        List<AttachmentFormat> l1 = JSON.parseArray(JSON.toJSONString(s), AttachmentFormat.class);
        List<AttachmentFormat> l2 = JSON.parseArray(JSON.toJSONString(s2), AttachmentFormat.class);

        if (l1 == null && l2 == null) {
            return true;
        }

        if (l1 == null) {
            return false;
        }

        if (l2 == null) {
            return false;
        }


        if (l1.size() != l2.size()) {
            return false;
        }

        List<String> id = l1.stream().map(a -> a.getId()).collect(Collectors.toList());
        List<String> id1 = l2.stream().map(a -> a.getId()).collect(Collectors.toList());


        return id.containsAll(id1);
    }

    /**
     * 转换驼峰
     *
     * @param str
     * @return
     */
    public static String toCamelCase(String str) {

        if (str == null || !str.contains("_")) {
            return str;
        }

        String s = Arrays.asList(str.split("_"))
                .stream()
                .map(a -> a.substring(0, 1).toUpperCase().concat(a.substring(1)))
                .collect(Collectors.joining());

        return s.substring(0, 1).toLowerCase().concat(s.substring(1));
    }

    /**
     * 获取选人控件id
     *
     * @param list
     * @return
     */
    public static String getSelectorFormatId(List<SelectorFormat> list) {
        if (list == null || list.size() == 0) return null;
        return list.get(0).getId();
    }

    /**
     * 获取选人控件id
     *
     * @param selectorFormat
     * @return
     */
    public static String getSelectorFormatId(SelectorFormat selectorFormat) {
        return selectorFormat != null ? selectorFormat.getId() : null;
    }

    /**
     * 获取选人控件name
     *
     * @param list
     * @return
     */
    public static String getSelectorFormatName(List<SelectorFormat> list) {
        if (list == null || list.size() == 0) return null;
        return list.get(0).getName();
    }

    /**
     * 获取选人控件name
     *
     * @param selectorFormat
     * @return
     */
    public static String getSelectorFormatName(SelectorFormat selectorFormat) {

        return selectorFormat != null ? selectorFormat.getName() : null;
    }

    /**
     * 解析object 返回 AddrFormat
     *
     * @param o
     * @return
     */
    public static AddrFormat getAddrFormat(Object o) {
        if (o == null) {
            return null;
        } else if (o instanceof AddrFormat) {
            return (AddrFormat) o;
        } else if (o instanceof String) {
            if (((String) o).startsWith("{")) {
                return JSON.parseObject(o.toString(), AddrFormat.class);
            } else if (((String) o).startsWith("[")) {
                JSONArray objects = JSON.parseArray(o.toString());
                if (objects.size() > 0) {
                    return JSON.toJavaObject((JSON) objects.get(0), AddrFormat.class);
                }
            }
        } else if (o instanceof List) {
            if (((List<?>) o).size() > 0 && ((List<?>) o).get(0) instanceof AddrFormat) {
                return (AddrFormat) ((List<?>) o).get(0);
            }
        }
        return null;
    }

    /**
     * 返回 地址详细
     *
     * @param addrFormat
     * @return
     */
    public static String getAddrFormatAddr(AddrFormat addrFormat) {
        String s = addrFormat != null ? addrFormat.getAddress() : null;
        return s != null ? s : "";
    }


    /**
     * 将长时间格式字符串转换为时间 yyyy-MM-dd HH:mm:ss
     *
     * @param strDate
     * @return
     */
    public static Date strToDate(String strDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ParsePosition pos = new ParsePosition(0);
        Date strtodate = formatter.parse(strDate, pos);
        return strtodate;
    }


    public static Integer objToInteger(Object obj) {

        if (NumberUtil.isInteger(String.valueOf(obj))) {
            return Integer.valueOf(obj.toString());
        } else {
            return null;
        }

    }


    public static boolean strEqualsArr(String str, String... strs) {
        for (String s : strs) {
            if (str.equals(s)){
                return true;
            }
        }
        return false;
    }
    /**
     * 外部接口参数非空校验
     * @param param 入参
     * @param type 类型 post或者get
     * @param keys 非空key
     * @return {@link GatewayResponse}
     * @throws
     * @author zhanjh
     * @date 2021/11/4 20:47
     */
    public static GatewayResponse isNotNullGatewayParam(GatewayParam param, String type, String... keys){
        Map<String,Object> body = null;
        if ("post".equals(type)){
            body = param.getBody();
        }else if("get".equals(type)){
            body = param.getQuery();
        }
        if (null == body || body.size() == 0){
            return GatewayResponse.failed("参数为空!");
        }
        for (String key : keys) {
            if (!body.containsKey(key) || null == body.get(key)){
                return GatewayResponse.failed("请求参数查询条件" + key + " 不能为空！");
            }
        }
        return GatewayResponse.success("数据校验成功！",body);
    }

}
